package com.sc.es.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author sc
 * Created on  2018/2/6
 *
 * 全局错误处理
 */
@Controller
public class MyErrorController implements ErrorController{

    private static final String ERROR_PATH="/error";
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @Autowired
    public MyErrorController(ErrorAttributes errorAttributes){
        this.errorAttributes=errorAttributes;
    }

    @RequestMapping(value = ERROR_PATH,produces = "text/html")
    public String errorPage(HttpServletRequest request, HttpServletResponse response){
        int status = response.getStatus();
        switch (status){
            case 403:
                return "403";
            case 404:
                return "404";
            case 500:
                return "500";
            default:
                return "index";
        }
    }

    /***
     * json/xml处理
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public ApiResponse errorApiHandler(HttpServletRequest request,HttpServletResponse response){
        RequestAttributes requestAttribute = new ServletRequestAttributes(request);
        Map<String,Object> attr = this.errorAttributes.getErrorAttributes(requestAttribute,false);
        int status = getStatus(request);
        return ApiResponse.ofMessage(status,String.valueOf(attr.getOrDefault("message","error ")));
    }

    private int getStatus(HttpServletRequest request){
        Integer status = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(status!=null){
            return status;
        }
        return 500;
    }

    @GetMapping("/404")
    public String notFound(){
        return "404";
    }
    @GetMapping("/403")
    public String accessError(){
        return "403";
    }
    @GetMapping("/500")
    public String internalError(){
        return "500";
    }
}
